package fourfaith.com.ff_sl21_app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.HashMap;
import java.util.Map;

import fourfaith.com.ff_sl21_app.AboutUsActivity;
import fourfaith.com.ff_sl21_app.ClearCacheActivity;
import fourfaith.com.ff_sl21_app.ExitActivity;
import fourfaith.com.ff_sl21_app.ModifyPwdActivity;
import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.VideoConfigActivity;
import fourfaith.com.ff_sl21_app.utils.APKVersionCodeUtils;
import fourfaith.com.ff_sl21_app.utils.CheckAppVer;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.DataCleanManager;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;
import fourfaith.com.ff_sl21_app.utils.version.AppVersionInfo;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link UserFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView exit,cacheSize;
    private TextView loginUserName;
    private LinearLayout videoConfigLayout,modifyPasswordLayout,aboutUsLayout,versionUpLayout,clearLayout;
    private RelativeLayout newAlert;
    private OnFragmentInteractionListener mListener;

    public UserFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static UserFragment newInstance(String param1, String param2) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user,container,false);
        initView(view);
        return view;
    }
    public void initView(View view){
        exit = (TextView)view.findViewById(R.id.exit);
        loginUserName = (TextView)view.findViewById(R.id.loginUserName);
        cacheSize = (TextView)view.findViewById(R.id.cacheSize);
        newAlert = (RelativeLayout)view.findViewById(R.id.newAlert);
        videoConfigLayout = (LinearLayout)view.findViewById(R.id.videoConfigLayout);
        modifyPasswordLayout = (LinearLayout)view.findViewById(R.id.modifyPasswordLayout);
        aboutUsLayout = (LinearLayout)view.findViewById(R.id.aboutUsLayout);
        versionUpLayout = (LinearLayout)view.findViewById(R.id.versionUpLayout);
        clearLayout = (LinearLayout)view.findViewById(R.id.clearLayout);
        SharedPreferences sharedPreferences =getActivity().getSharedPreferences(Constants._loginInfo, Context.MODE_PRIVATE);
        loginUserName.setText(sharedPreferences.getString("userName",""));
        String cachePathSize = null;
        try {
            cachePathSize = DataCleanManager.getCacheSize(getContext().getExternalCacheDir());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(cachePathSize.contains("Byte")){
          /*  cacheSize.setText("");*/
            cacheSize.setText(cachePathSize);
        }else{
            cacheSize.setText(cachePathSize);
        }
        videoConfigLayout.setOnClickListener(listener);
        modifyPasswordLayout.setOnClickListener(listener);
        aboutUsLayout.setOnClickListener(listener);
        versionUpLayout.setOnClickListener(listener);
        clearLayout.setOnClickListener(listener);
        exit.setOnClickListener(listener);
        CheckVersion();
    }
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.videoConfigLayout:
                        Intent videoConfigIntent = new Intent();
                        videoConfigIntent.setClass(getActivity(), VideoConfigActivity.class);
                        startActivityForResult(videoConfigIntent, 1);
                        break;
                    case R.id.modifyPasswordLayout:
                        Intent modifyPwdIntent = new Intent();
                        modifyPwdIntent.setClass(getActivity(), ModifyPwdActivity.class);
                        startActivityForResult(modifyPwdIntent, 1);
                        break;
                    case R.id.aboutUsLayout:
                        Intent aboutUsIntent = new Intent();
                        aboutUsIntent.setClass(getActivity(), AboutUsActivity.class);
                        startActivityForResult(aboutUsIntent, 1);
                        break;
                    case R.id.clearLayout:
                        if(cacheSize.getText().toString().equals("0.0Byte")){
                            Toast.makeText(getActivity(), "暂无可清理的缓存", Toast.LENGTH_SHORT).show();
                        }else{
                            Intent clearIntent = new Intent();
                            clearIntent.setClass(getActivity(), ClearCacheActivity.class);
                            startActivityForResult(clearIntent, 1);
                        }
                        break;
                    case R.id.versionUpLayout:
                        CheckAppVer.getInstance().checkVersion(getContext());
                        break;
                    case R.id.exit:
                        Intent exitIntent = new Intent();
                        exitIntent.setClass(getActivity(), ExitActivity.class);
                        startActivityForResult(exitIntent, 1);
                        break;
                }
        }
    };
    public void CheckVersion(){
        Map<String, String> params = new HashMap<>();
        RequestQueue mQueue = RequestQueueSingleton.getInstance(getContext()).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, Constants.versionInfo, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {
                        JSONObject dataObj = (JSONObject) responseResult.getData();
                        AppVersionInfo appVerInfo = new AppVersionInfo();
                        appVerInfo.setVerCode(dataObj.getString("verCode"));
                        appVerInfo.setDownUrl(dataObj.getString("downUrl"));
                        if (appVerInfo != null && appVerInfo.getVerCode() != null && !appVerInfo.getVerCode().equals(String.valueOf(APKVersionCodeUtils.getVersionCode(getContext())))) {
                            newAlert.setVisibility(View.VISIBLE);
                        }else{
                            Toast.makeText(getActivity(), "当前是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        },params);
        mQueue.add(jsonRequest);
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
